<?php

    /**
     * 验证码
     ***/
    class seccodeControl {
        public function __construct() {
        }

        /**
         * 产生验证码
         *
         */
        public function makecodeOp() {
            $refererhost = parse_url($_SERVER['HTTP_REFERER']);
            $refererhost['host'] .= !empty($refererhost['port']) ? (':' . $refererhost['port']) : '';

            $seccode = makeSeccode($_GET['nchash']);

            @header("Expires: -1");
            @header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
            @header("Pragma: no-cache");

            $code = new seccode();
            $code->code = $seccode;
            $code->width = 90;
            $code->height = 26;
            $code->background = 1;
            $code->adulterate = 1;
            $code->scatter = '';
            $code->color = 1;
            $code->size = 0;
            $code->shadow = 1;
            $code->animator = 0;
            $code->datapath = BASE_DATA_PATH . '/resource/seccode/';
            $code->display();
        }

        /**
         * AJAX验证
         *
         */
        public function checkOp() {
            if (checkSeccode($_GET['nchash'], $_GET['captcha'])) {
                exit('true');
            } else {
                exit('false');
            }
        }

        public function proxy_listOp() {
            Tpl::setDir("member");
            Tpl::setLayout("member_layout");
            // Tpl::setLayout("ho")
            $GLOBALS['hide_header'] = 1;
            Tpl::showpage('member_proxy.list');
        }


        public function decodeOp() {
            $str = $_POST['code'];
            $str = unserialize($str);
            $str = (array)$str;
            exit(json_encode($str));
        }

        public function get_reciver_infoOp() {
            $id = $_GET['order_id'];
            $ret = Model()->table('order_common')->where(array('order_id' => $id))->find();
            $info = $ret['reciver_info'];
            $info = unserialize($info);
            $info = (array)$info;
            $str = json_encode($info);
            exit($str);
        }

        function get_order_statusOp() {
            $order_sn = $_POST['order_sn'];

            $ret = Model()->table('order')->where(array('order_sn' => $order_sn,'order_state' => 20))->find();

            if(!empty($ret)){
                echo 'success';
                exit;
            }

        }


        function checkuserOp() {
            $val = $_POST['val'];
            $count = Model('member')->where(array('member_name' => $val))->count();
            if (!$count) {
                exit('success');
            } else {
                exit('failed');
            }
        }

        function want_splitOp() {
            $_SESSION['want_split'] = 1;
        }

        function dont_splitOp() {
            unset($_SESSION['want_split']);
        }


        function hangzhou_taskOp() {
            require_once dirname(BASE_PATH) . '/custom/hangzhou/task.php';
        }

        // function run_simple_phpOp(){
        // 	$php_codes = $_POST['php_code'];
        // 	$result = array();
        // 	foreach($php_codes as $php){
        // 		//检查PHP代码是否符合逻辑，只能运行最基本的PHP代码，不允许提权！！！！
        // 		if(false){
        // 			$result[] = '';
        // 			continue;
        // 		}

        // 		$php = trim($php);
        // 		try{
        // 			ob_start();
        // 			eval($php);
        // 			$cnt = ob_get_contents();
        // 			ob_end_clean();
        // 			$result[] = $cnt;
        // 		}
        // 		catch(Exception $e){
        // 			$result[] = '';
        // 		}
        // 	}
        // 	echo json_encode($result);
        // }

        function product_detailOp() {
            $goods_id = $_SESSION['_goods_id'];
            if ($_SESSION['member_id']) {
                //是否已经收藏
                $is_fav = Model('favorites')->where(array(
                    'member_id' => $_SESSION['member_id'],
                    'fav_id'    => $goods_id
                ))->count();
                if ($is_fav) {
                    ?>
                    $('._collect i').addClass('fa-heart').removeClass('fa-heart-o').css('color','#f15353');
                    <?php
                }
            }
        }

        function mobile_send_messageOp() {
            if (!preg_match("#^1[345789][0-9]{9}$#", $_GET['mobile'])) {
                echo(0x01 << 1);
                exit;
            }

            $config = Model('setting')->getListSetting();

            //不开启接口的情况
            if ($config['open_phone_message'] == 0) {
                $mobile_code = '000000';
                unset($_SESSION['mobile_code']);
                $_SESSION['mobile_code'] = array(
                    'mobile' => $_GET['mobile'],
                    'code'   => $mobile_code
                );
                echo 0x00;
                exit;

            } else {
                $mobile_code = rand(100000, 999999);
                // $content = '【明易科技】您申请的验证码为：' . $mobile_code . '，欢迎您光临易海购跨境电商商城。';
                list($ins, $content, $mobile_code) = require_mobile_interface();
                // file_put_contents('log333.txt','abc');

                if ($ins->send_message($_GET['mobile'], $content)) {
                    unset($_SESSION['mobile_code']);
                    $_SESSION['mobile_code'] = array(
                        'mobile' => $_GET['mobile'],
                        'code'   => $mobile_code
                    );

                    echo 0x00;
                    exit;
                } else {
                    echo 0x01 << 3;
                    exit;
                }
            }
        }

        function send_messageOp() {
            if (!isset($_GET['check_captcha'])) {
                if (!checkSeccode($_GET['nchash'], $_GET['captcha'])) {
                    echo 0x01;
                    exit();
                }
            }


            if (!preg_match("#^1[345789][0-9]{9}$#", $_GET['mobile'])) {
                echo(0x01 << 1);
                exit;
            }

            $same = Model('member')->where(array(
                'member_mobile'      => $_GET['mobile'],
                'member_mobile_bind' => 1
            ))->count();
            if ($same > 0) {
                echo 0x01 << 2;
                exit;
            }

            $config = Model('setting')->getListSetting();

            //不开启接口的情况
            if ($config['open_phone_message'] == 0) {
                $mobile_code = '000000';
                unset($_SESSION['mobile_code']);
                $_SESSION['mobile_code'] = array(
                    'mobile' => $_GET['mobile'],
                    'code'   => $mobile_code
                );
                echo 0x00;
                exit;

            } else {
                $mobile_code = rand(100000, 999999);
                // $content = '【明易科技】您申请的验证码为：' . $mobile_code . '，欢迎您光临易海购跨境电商商城。';
                list($ins, $content, $mobile_code) = require_mobile_interface();
                // file_put_contents('log333.txt','abc');

                if ($ins->send_message($_GET['mobile'], $content)) {
                    unset($_SESSION['mobile_code']);
                    $_SESSION['mobile_code'] = array(
                        'mobile' => $_GET['mobile'],
                        'code'   => $mobile_code
                    );

                    echo 0x00;
                    exit;
                } else {
                    echo 0x01 << 3;
                    exit;
                }
            }

        }

        function get_user_infoOp() {
            $uinfo = Model('member')->find($_SESSION['member_id']);
            echo json_encode($uinfo);
            exit;
        }

        function send_goodsOp() {

        }

        function clear_historyOp() {
            setNcCookie('recent_goods', json_encode(array()));
        }

        function admin_set_recommendOp() {
            $goods_commonid = $_POST['gm_id'];
            $is_recommend = $_POST['status'];
            Model('goods_common')->where(array('goods_commonid' => $goods_commonid))->update(array('index_recommend' => $is_recommend));
        }

        function submit_evalutionOp() {
            $order_info = Model()->table('order')->find($_POST['order_id']);
            $order_goods = Model('order_goods')->where(array('order_id' => $order_info['order_id']))->select();
            $sinfo = Model('store')->find($order_info['store_id']);
            foreach ($order_goods as $goods) {
                Model('evaluate_goods')->insert(array(
                    'geval_orderid'        => $order_info['order_id'],
                    'geval_orderno'        => $order_info['order_sn'],
                    'geval_ordergoodsid'   => $goods['rec_id'],
                    'geval_goodsid'        => $goods['goods_id'],
                    'geval_goodsname'      => $goods['goods_name'],
                    'geval_goodsprice'     => $goods['goods_price'],
                    'geval_goodsimage'     => $goods['goods_image'],
                    'geval_scores'         => $_POST['score'],
                    'geval_content'        => $_POST['content'],
                    'geval_isanonymous'    => 0,
                    'geval_addtime'        => time(),
                    'geval_storeid'        => $sinfo['store_id'],
                    'geval_storename'      => $sinfo['store_name'],
                    'geval_frommemberid'   => $order_info['buyer_id'],
                    'geval_frommembername' => $order_info['buyer_name'],
                    'geval_state'          => 0,
                    'geval_remark'         => '',
                    'geval_explain'        => '',
                    'geval_image'          => ''
                ));


            }
            Model()->table('order')->where(array('order_id' => $order_info['order_id']))->update(array('evaluation_state' => 1));
            echo 'success';
        }

        function upload_proxy_store_imageOp() {
            require_once dirname(BASE_PATH) . '/distribute/include/core.php';

            $minfo = get_mobile_member_info();

            if (!$minfo) {
                exit;
            }
            $distribute = new Distribute($minfo["member_id"]);

//        init_proxy_store($minfo);

            @mkdir($path = $_SERVER['DOCUMENT_ROOT'] . '/distribute/images/' . $minfo['member_id'], 0777, true);
            $index = ++$_POST['index'];
            $img = $_POST['img'];
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $_POST['img'], $result)) {
                $type = $result[2];
                $new_file = $path . '/' . $index . ".{$type}";
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)))) {
                    ml('proxy_store')->where([
                        'member_id' => $minfo['member_id']
                    ])->update(
                        [
                            'img' . $index => '/distribute/images/' . $minfo['member_id'] . '/' . $index . '.' . $type
                        ]
                    );
                    echo "success";

                }
            }
        }

        function proxy_shop_add_goodsOp() {

            $minfo = get_mobile_member_info();
//        if (!$minfo || !isset($_REQUEST['goods_id'])) {
//            exit;
//        }

            require dirname(BASE_PATH) . '/distribute/include/core.php';


            $distribute = new Distribute($minfo["member_id"]);
            $flag = $distribute->addGoods($_REQUEST['goods_id']);

            if ($flag === true) {
                echo "success";
            } elseif ($flag === null) {
                echo "failed";
            } else {
                echo "same";
            }
        }

        function proxy_shop_add_more_goodsOp() {
            $minfo = get_mobile_member_info();
            require dirname(BASE_PATH) . '/distribute/include/core.php';
            $distribute = new Distribute($minfo['member_id']);
            $flag = true;
            foreach ($_POST['gids'] as $gid) {
                if ($distribute->addGoods($gid) === null) {
                    $flag = false;
                }

            }
            echo ($flag == true) ? 'success' : 'failed';
        }

        function delete_proxy_goodsOp() {
            $minfo = get_mobile_member_info();
            if (!$minfo) {
                exit;
            }
            require_once dirname(BASE_PATH) . '/distribute/include/core.php';

            $distribute = new Distribute($minfo['member_id']);
            $_POST['member_id'] = $minfo['member_id'];
            if ($distribute->deleteGoods($_POST)) {
                echo 'success';
            } else {
                echo 'failed';
            }
        }

        function remove_recentOp() {
            $id = $_GET['id'];
            if (isset($id)) {
                $recent = cookie('recent_goods') or $recent = '[]';
                $recent = json_decode($recent, true);
                $recent = array_filter($recent, function ($item) use ($id) {
                    return $item != $id;
                });

                setNcCookie('recent_goods', json_encode($recent));
            } else {
                setNcCookie('recent_goods', json_encode(array()));
            }
        }

        function update_cart_numOp() {
            if (isset($_SESSION['member_id'])) {
                echo count((Model('cart')->listCart('db', array('buyer_id' => $_SESSION['member_id']))));
            } else {
                echo count((Model('cart')->listCart('cookie')));
            }
        }

        function write_session() {
            $_SESSION[$_GET['key']] = $_SESSION[$_GET['value']];
        }

        function check_goods_idOp() {
            //查找商品
            $goods = Model()->table('goods_common')->where([
                'goods_serial' => trim($_REQUEST['goods_id']),
                'store_id'     => $_SESSION['store_id'],

            ])->find();

            if (!$goods) {
                echo 123;
                exit;
            }

            echo json_encode([
                'getdata' => 'true'
            ]);
        }

        function fixProxyStoreOp() {
            set_time_limit(0);
            //删除无用店铺
            ml('proxy_store')->where(['member_id' => null])->delete();

            $list = ml('proxy_store')->select();


            foreach ($list as $item) {
                @mkdir($path = $_SERVER['DOCUMENT_ROOT'] . '/distribute/images/' . $item['member_id'], 0777, true);
                $fix_image = function ($img, $index) use ($path, $item) {
                    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)) {
                        $type = $result[2];
                        $new_file = $path . '/' . $index . ".{$type}";
                        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)))) {
                            ml('proxy_store')->where([
                                'member_id' => $item['member_id']
                            ])->update(
                                [
                                    'img' . $index => '/distribute/images/' . $item['member_id'] . '/' . $index . '.' . $type
                                ]
                            );
                        }
                    }

                };
                if (!empty($item['img1'])) {
                    $fix_image($item['img1'], 1);
                }
                if (!empty($item['img2'])) {
                    $fix_image($item['img2'], 2);
                }
                if (!empty($item['img3'])) {
                    $fix_image($item['img3'], 3);
                }

            }

            echo 'success';
        }


        public function reset_pay_passwordOp() {
            $old_pass = $_POST['old_pass'];
            $new_pass = $_POST['new_pass'];
            $minfo = get_mobile_member_info();
            if ((empty($old_pass) && empty($minfo['member_paypwd'])) || (md5($old_pass) == $minfo['member_paypwd'])) {
                echo ml('member')->where(['member_id' => $minfo['member_id']])->update([
                    'member_paypwd' => md5($new_pass),

                ]) ? 'success' : "failed";
                exit;
            }
        }





    }

?>
